<!doctype html>



  


<html class="theme-next mist use-motion" lang="en">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="JavaScript Closure学习JavaScript，不能不知道闭包(closure)的概念和作用。闭包是JavaScript中重要的一个概念，对于初学者来讲，闭包很难理解和运用。但只有理解了闭包的基本概念，才能正确的使用它；同样的，只有配合正确的实践，我们才有更加深刻的理解。因此，这片文章借鉴了很多前人的总结和经验，只为更好的理解闭包。    闭包的概念对于码农来说，学习一门新技术，除了">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript学习笔记(3)">
<meta property="og:url" content="http://yoursite.com/2016/03/27/JavaScript学习笔记-3/index.html">
<meta property="og:site_name" content="Ji Xiang&#39;s blog">
<meta property="og:description" content="JavaScript Closure学习JavaScript，不能不知道闭包(closure)的概念和作用。闭包是JavaScript中重要的一个概念，对于初学者来讲，闭包很难理解和运用。但只有理解了闭包的基本概念，才能正确的使用它；同样的，只有配合正确的实践，我们才有更加深刻的理解。因此，这片文章借鉴了很多前人的总结和经验，只为更好的理解闭包。    闭包的概念对于码农来说，学习一门新技术，除了">
<meta property="og:locale" content="en">
<meta property="og:updated_time" content="2018-11-18T02:59:33.028Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript学习笔记(3)">
<meta name="twitter:description" content="JavaScript Closure学习JavaScript，不能不知道闭包(closure)的概念和作用。闭包是JavaScript中重要的一个概念，对于初学者来讲，闭包很难理解和运用。但只有理解了闭包的基本概念，才能正确的使用它；同样的，只有配合正确的实践，我们才有更加深刻的理解。因此，这片文章借鉴了很多前人的总结和经验，只为更好的理解闭包。    闭包的概念对于码农来说，学习一门新技术，除了">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2016/03/27/JavaScript学习笔记-3/"/>





  <title> JavaScript学习笔记(3) | Ji Xiang's blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">Ji Xiang's blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle">Walk step by step and learn everyday</p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://yoursite.com/2016/03/27/JavaScript学习笔记-3/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Ji Xiang">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="http://o7bp9e1ec.bkt.clouddn.com/1485173143816">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="Ji Xiang's blog">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="Ji Xiang's blog" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                JavaScript学习笔记(3)
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2016-03-27T16:47:19+08:00">
                2016-03-27
              </time>
            

            

            
          </span>

          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="JavaScript-Closure"><a href="#JavaScript-Closure" class="headerlink" title="JavaScript Closure"></a>JavaScript Closure</h1><p>学习JavaScript，不能不知道<b>闭包(closure)</b>的概念和作用。闭包是JavaScript中重要的一个概念，对于初学者来讲，闭包很难理解和运用。但只有理解了闭包的基本概念，才能正确的使用它；同样的，只有配合正确的实践，我们才有更加深刻的理解。因此，这片文章借鉴了很多前人的总结和经验，只为更好的理解闭包。   </p>
<h2 id="闭包的概念"><a href="#闭包的概念" class="headerlink" title="闭包的概念"></a>闭包的概念</h2><p>对于码农来说，学习一门新技术，除了看官方API和相关文档，示例代码的对我们的帮助可能更大，因为代码的运行结果更加直观，能加深我们的理解。下面贴出大牛的代码，号称世上最简单的闭包：   </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">A</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">B</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'Hello closure!'</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> B;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> c = A();</span><br><span class="line"><span class="comment">// c(); Hello closure!</span></span><br></pre></td></tr></table></figure>
<p>确实，这个示例代码真的不能再简单了。这段代码“翻译”后可以表示为：   </p>
<ol>
<li>定义了一个函数A   </li>
<li>在A中定义了内部函数B   </li>
<li>在A中返回B（确切的讲，在A中返回B的引用）   </li>
<li>执行A()，把A的返回值-函数B()的引用复制给变量c   </li>
<li>执行 函数B()，输出结果</li>
</ol>
<p>根据上述例子，闭包可定义为：<br><em>当一个内部函数被其外部函数之外的变量引用时，就形成了一个闭包。</em></p>
<h2 id="闭包的作用"><a href="#闭包的作用" class="headerlink" title="闭包的作用"></a>闭包的作用</h2><p>在了解闭包的作用之前，我们先了解一下JavaScript中的垃圾回收(GC)机制：<em>在JavaScript中，如果一个对象不再被引用，那么这个对象就会被GC回收，否则这个对象会一直保存在内存中。</em><br>在上述例子中，B定义在A中，因此B依赖于A，而外部变量c获得了内部函数B的引用，也就是说，A被间接引用了，所以A不会被GC回收，而是一直保持上下文，在同一个引用调用结束前，会一直保存在内存中，直到调用结束。<br>示例2：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">A</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> count = <span class="number">0</span>;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">B</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    count++;</span><br><span class="line">    <span class="built_in">console</span>.log(count);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> B;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> c = A();</span><br><span class="line">c();<span class="comment">//1</span></span><br><span class="line">c();<span class="comment">//2</span></span><br><span class="line">c();<span class="comment">//3</span></span><br></pre></td></tr></table></figure>
<p>count是A中的一个变量，它的值在B中被改变，函数B每执行一次，count的值在原来的基础上累加1，A被变量c引用，不会被GC，因此，A中的count一直保存在内存中，c每执行一次，由于保留了上下文，count的值会在原来的基础上增加1。<br>这就是闭包的作用，有时候我们需要一个模块中定义这样一个变量：希望这个变量一直保存在内存中，但又不会“污染”全局的变量，这个时候，我们就可以用闭包来定义这个模块。</p>
<h3 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h3><p>上面的例子只是最简陋的写法，实际中不会这么写。这里只是为了加深理解。当然，如果要全面理解闭包，仅凭上面的文字和代码是远远不够的。在项目中不妨试着使用闭包，用的多了自然会有独到的理解。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/03/23/JavaScript学习笔记-2/" rel="next" title="JavaScript学习笔记(2)">
                <i class="fa fa-chevron-left"></i> JavaScript学习笔记(2)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/03/28/course-note-2/" rel="prev" title="信息系统管理与安全(2)">
                信息系统管理与安全(2) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://o7bp9e1ec.bkt.clouddn.com/1485173143816"
               alt="Ji Xiang" />
          <p class="site-author-name" itemprop="name">Ji Xiang</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">posts</span>
              </a>
            </div>
          

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#JavaScript-Closure"><span class="nav-number">1.</span> <span class="nav-text">JavaScript Closure</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#闭包的概念"><span class="nav-number">1.1.</span> <span class="nav-text">闭包的概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#闭包的作用"><span class="nav-number">1.2.</span> <span class="nav-text">闭包的作用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#结语"><span class="nav-number">1.2.1.</span> <span class="nav-text">结语</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ji Xiang</span>
</div>


<div class="powered-by">
  Powered by <a class="theme-link" href="https://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  

  
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid="></script>
      <!-- UY END -->
  




  
  

  

  

  

  


</body>
</html>
